<!--
 * @Description: 数据字典多选组件
 * @Author: zhailei
 * @Date: 2021-06-02 13:38:08
 * @LastEditTime: 2021-09-17 09:25:08
 * 
 * @FilePath: \vite-demoe:\wwwroot\Vue\\-cloud-vue\src\components\TopVUI\dict\TMultiSelectTag.vue
-->
<template>
  <!-- 复选框 -->
  <a-checkbox-group
    v-if="tagType == 'checkbox'"
    @change="onChange"
    :value="arrayValue"
    :disabled="disabled"
  >
    <a-checkbox
      v-for="(item, key) in dictOptions"
      :key="key"
      :class="showCode"
      :value="getValue(item)"
    >
      {{
        dataType == "dynamic" && dynamic
          ? item[showCode]
          : item.label || item.dicItemName
      }}</a-checkbox
    >
  </a-checkbox-group>
  <!-- 下拉多选 -->
  <a-select
    style="width: 100%;"
    v-else-if="tagType == 'select'"
    option-filter-prop="children"
    :value="arrayValue"
    @change="onChange"
    :disabled="disabled"
    mode="multiple"
    :placeholder="placeholder"
    :getPopupContainer="(node) => node.parentNode"
    :allowClear="allowClear"
  >
    <a-select-option
      v-for="(item, index) in dictOptions"
      :key="index"
      :value="getValue(item)"
    >
      {{
        dataType == "dynamic" && dynamic
          ? item[showCode]
          : item.label || item.dicItemName
      }}
    </a-select-option>
  </a-select>
</template>

<script>
import { getObjectByString, debounce } from "@/utils/util";
export default {
  name: "TMultiSelectTag",
  inject: {
    sameValue: {
      default: undefined,
    },
    extraParamsValue: { default: undefined },
  }, //静态值时保存值与显示值一致
  props: {
    dictCode: String,
    placeholder: String,
    disabled: Boolean,
    value: String,
    type: String,
    options: Array,
    dataList: Array,
    saveCode: String,
    showCode: String,
    url: "",
    dataType: {
      type: String,
      default: "code",
    },
    params: {},
    method: {
      type: String,
      default: "post",
    },
    allowClear: {
      type: Boolean,
      default: true,
    },
    attributeObj: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      dictOptions: [],
      tagType: "",
      arrayValue:
        !this.value || !this.value.length ? [] : this.value.split(","),
      dynamic: true, //当切换数据获取方式  拥有saveCode时切换数据方式会无法渲染字典格式
    };
  },
  created() {
    if (!this.type || this.type === "list_multi") {
      this.tagType = "select";
    } else {
      this.tagType = this.type;
    }
    //获取字典数据
    //this.initDictData();
  },
  watch: {
    options: function(val) {
      this.setCurrentDictOptions(val);
    },
    // 请求方式
    dataType: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal === "static") {
          this.dictOptions = this.dataList;
          this.dynamic = false;
        } else if (newVal === "dynamic") {
          this.getDataList();
          this.dynamic = true;
        } else {
          this.initDictData();
          this.dynamic = true;
        }
      },
    },
    // 监听值的变化
    value(val) {
      if (!val) {
        this.arrayValue = [];
      } else {
        this.arrayValue = this.value.split(",");
      }
    },
    params: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (oldVal) {
          debounce(() => {
            this.getDataList();
            // 注释原因：请查看当前目录下TDictSelectTag.vue相同位置
          }, 200);
        }
      },
    },
    dataList: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (oldVal) {
          this.dictOptions = newVal;
        }
      },
    },
    dictCode: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal && this.dataType === "code") {
          this.initDictData();
        }
      },
    },
    attributeObj: {
      deep: true,
      immediate: true,
      handler(newVal, oldVal) {
        if (newVal && newVal.dataType === "dynamic" && newVal.url) {
          this.getDataList();
        }
      },
    },
  },
  methods: {
    // 返回是否需要保存值一致
    getValue(item) {
      // 动态值
      if (this.dataType == "dynamic" && this.dynamic) {
        return item[this.saveCode];
      } else if (this.sameValue && !this.dynamic) {
        //切换值属性会自动切换dynamic 可以不做  （需要值与显示一致）
        return item.dicItemName;
      } else {
        //不需要值与显示一致
        return item.dicItemCode;
      }
    },
    // JSON格式数据转JS格式
    parseData(data) {
      try {
        // 尝试 JSON.parse 两次
        const parsedData = JSON.parse(JSON.parse(data));
        return parsedData;
      } catch (error) {
        try {
          // 如果报错，再尝试 JSON.parse 一次
          const parsedData = JSON.parse(data);
          return parsedData;
        } catch (error) {
          // 如果再次报错，返回原始数据
          return data;
        }
      }
    },
    // 获取动态数组
    getDataList() {
      this.$post(
        "/system/sysInterfaceManagement/getDetailByUuid",
        this.params
      ).then((detailRes) => {
        if (detailRes.statusCode === 200) {
          let extraParams = this.extraParamsValue?.() ?? {};
          this.$axios(this.method, this.url, {
            ...this.params,
            ...extraParams,
          }).then((res) => {
            if (res.statusCode === 200) {
              this.$nextTick(() => {
                try {
                  const fun = eval(JSON.parse(detailRes.data.dataFilter));
                  if (detailRes.data.interfaceType === "intetface_type.01") {
                    this.dictOptions = this.parseData(res.data);
                  } else if (
                    detailRes.data.interfaceType === "intetface_type.02"
                  ) {
                    res.data = this.parseData(res.data);
                    this.dictOptions = fun(res.data);
                  } else if (
                    detailRes.data.interfaceType === "intetface_type.03"
                  ) {
                    this.dictOptions = fun(res);
                  }
                } catch (e) {
                  console.log(e);
                }
              });
            }
          });
        }
      });
    },
    // 获取字典数据
    initDictData() {
      this.$post(
        "/system/dicSet/getDicItemByCode",
        {
          code: this.dictCode,
        },
        null
      ).then((res) => {
        if (res.statusCode === 200) {
          this.dictOptions = res.data;
          this.dynamic = false; //这里暂时未做获取不到清除选项  后续添加需要更新dynamic的显示
        }
      });
    },
    onChange(selectedValue) {
      this.$emit("change", selectedValue.join(","));
    },
    setCurrentDictOptions(dictOptions) {
      this.dictOptions = dictOptions;
    },
    getCurrentDictOptions() {
      return this.dictOptions;
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
};
</script>
